// GA日志统计
const GAEvent = (eventname: string, gaAttrs = {}) => {
    window.gtag('event', eventname, gaAttrs)
    console.log(eventname, gaAttrs);
    window.posthog.capture(eventname, gaAttrs)
}

// Tiktok事件
const TiktokEvent = (eventname: string) => {
    if (eventname === 'GAM_Inter_Click_Auto') {
        window.ttq.track('AddPaymentInfo')
        window.ttq.track('AddToCart')
    }
    if (eventname === 'GAM_Anc_Click_Auto') {
        window.ttq.track('AddToWishlist')
    }

    if (eventname === 'GAM_AD_Click_All') {
        // const clickCount = Number(sessionStorage.getItem('_trackCount')) || 0;
        // const clickMap = clickCount % 3
        // if (clickMap === 2) {
        //     window.ttq.track('Purchase');
        //     console.log('[Tiktok]', 'Purchase')
        // }
        window.ttq.track('ClickButton');
    }

    if (eventname === 'Sum_AD_Click_All') {
        window.ttq.track('ViewContent');
    }
}

// Bigo事件
const BigoEvent = (eventname: string, attrs = {}) => {
    if (eventname === 'AD_Click') {
        const eventList = ['button', 'ec_detail_view','ec_add_cart'];
        const clickCount = Number(sessionStorage.getItem('_trackCount')) || 0;
        const eventName = eventList[clickCount % 3];
        
        console.log('[Bigo]', eventName, attrs)
        window.bge('event', eventName, attrs);
    }
}


const getParams = () => {
    const params = Object.fromEntries(useRequestURL().searchParams)
    // 将每一项属性名首字母大写
    const newParams: Record<string, string> = {}
    for (const key in params) {
        newParams[key.charAt(0).toUpperCase() + key.slice(1)] = params[key]
    }
    return newParams
}
    
export const logEvent = async (eventname: string, attrs = {}) => {
    const queryParams = getParams()
    let page = window.location.pathname.split('/')[1];
    
    const pageMap: Record<string, string> = {
        '': 'Home',
        'detail': 'Detail',
        'search-input': 'Search',
        'search': 'SearchResult',
        'favorite': 'Favorite'
    };
    page = pageMap[page] || page;
    const gaAttrs = {...queryParams, ...attrs, page: page}
    const network = queryParams.Network || ''
    
    GAEvent(eventname, gaAttrs)
    
    switch (network) {
        case 'tiktok':
            TiktokEvent(eventname)
            break
        case 'bigo':
            BigoEvent(eventname, attrs)
            break
        default:
            break
    }
}
